package com.bgds.sys.config.influx;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.BatchOptions;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.function.BiConsumer;

/**
 * influxDb配置
 * @author lj
 */
@Slf4j
@Configuration
@Data
public class InfluxConfig {

    @Value("${spring.influx.database}")
    private String influxDatabase;
    @Value("${spring.influx.url}")
    private String influxUrl;
    @Value("${spring.influx.user}")
    private String influxUser;
    @Value("${spring.influx.password}")
    private String influxPassword;
    /**
     * 数据保存策略
     * --查询策略
     * show retention policies on bgds
     *
     * --修改策略
     * alter retention policy "bgds_policy" on "bgds" duration 730d replication 1 default;
     */
    public static String policyNamePix = "bgds_policy";

    @Bean
    public InfluxDB createInfluxDb() {
        InfluxDB influxDb = InfluxDBFactory.connect(influxUrl, influxUser, influxPassword);
        BiConsumer<Iterable<Point>, Throwable> exceptionHandler = (batch, exception) -> {
            //批量插入失败
            log.error("influxDB 批量插入失败");
            exception.printStackTrace();
        };

        /**
         * 设置批量插入，满足条件10000条开始插入
         */
        BatchOptions options = BatchOptions.DEFAULTS.actions(20000).flushDuration(1000).exceptionHandler(exceptionHandler);
        //开启批量插入
        influxDb.enableBatch(options);
        influxDb.setDatabase(influxDatabase);
        //设置保留策略
        influxDb.setRetentionPolicy(policyNamePix);
        return influxDb;
    }

}
